package com.project.poetry.service.service.impl;

import com.project.poetry.service.entity.dto.statistics.StatisticsAuthorPoetryDTO;
import com.project.poetry.service.entity.dto.statistics.StatisticsDTO;
import com.project.poetry.service.entity.dto.statistics.StatisticsResultDTO;
import com.project.poetry.service.mapper.StatisticsMapper;
import com.project.poetry.service.service.StatisticsService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 统计业务层实现类
 * @author mengxj
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class StatisticsServiceImpl implements StatisticsService {

    @Resource
    private StatisticsMapper statisticsMapper;

    @Override
    public StatisticsResultDTO statisticsResult() {
        List<StatisticsDTO> statisticsList = this.statisticsMapper.statisticsResult();
        List<String> dynastyRes = new ArrayList<>();
        List<Integer> authorRes = new ArrayList<>(), poetryRes = new ArrayList<>(), typeRes = new ArrayList<>();
        int maxPoetry = 0, maxAuthor = 0, maxType = 0;
        for(StatisticsDTO statistics : statisticsList){
            dynastyRes.add(statistics.getDynasty());
            Integer author = statistics.getAuthor();
            authorRes.add(author);
            Integer poetry = statistics.getPoetry();
            poetryRes.add(poetry);
            Integer type = statistics.getType();
            typeRes.add(type);
            if(maxPoetry < poetry){
                maxPoetry = poetry;
            }
            if(maxAuthor < author){
                maxAuthor = author;
            }
            if(maxType < type){
                maxType = type;
            }
        }
        return StatisticsResultDTO.builder().authorRes(authorRes).dynastyRes(dynastyRes).poetryRes(poetryRes)
                .typeRes(typeRes).maxPoetry(maxPoetry).maxAuthor(maxAuthor).maxType(maxType).build();
    }

    @Override
    public StatisticsAuthorPoetryDTO statisticsAuthorPoetry(){
        List<StatisticsAuthorPoetryDTO.StatisticsAuthorPoetryInDTO> statisticsList = this.statisticsMapper.statisticsAuthorPoetry();
        StatisticsAuthorPoetryDTO res = new StatisticsAuthorPoetryDTO();
        res.setList(statisticsList);
        res.setNames(statisticsList.stream().map(StatisticsAuthorPoetryDTO.StatisticsAuthorPoetryInDTO :: getName).collect(Collectors.toList()));
        return res;
    }
}
